<template>
    <div>
        <Card :bordered="false" :shadow="false" dis-hover>
            <p slot="title" style="color: #969896"><Icon type="ios-alert-outline" style="margin-right: 5px" color="orange" />
                录入或修改教师信息,请输入身份证号来判定是否重复(单纯修改员工照片无需提交)
                <Button type="text" @click="handleSubmit" v-loading.fullscreen.lock="fullscreenLoading" style="float: right;margin-top: -5px">提交</Button>
            </p>

            <Form ref="form" @on-validate="onValidate" :model="teacher" hide-required-mark inline :label-width="70" label-position="right">

                <Divider orientation="right">基础信息</Divider>
                <Row>
                    <Col :span="14">
                        <FormItem prop="idCard" label="身份证号" :rules="[{validator:$validated.isCard},{min:15,max:18,message:'15~18个字符',trigger:'blur'}]">
                            <Input v-model="teacher.idCard" :disabled="show" @on-blur="searchTeacher(teacher.idCard)" placeholder="请输入正确的身份证号" style="width: 300px" :maxlength="18" prefix="ios-card-outline" show-word-limit />
                        </FormItem>
                        <FormItem prop="nickName" label="教师姓名" :rules="[{validator:$validated.onlyChinese,trigger:'blur'},{min:2,max:5,message:'2~5个字符',trigger:'blur'}]">
                            <Input v-model="teacher.nickName" :disabled="ok" @on-change="createUsername" placeholder="请输入教师姓名" style="width: 300px" :maxlength="5" prefix="ios-person-outline" show-word-limit />
                        </FormItem>
                        <FormItem prop="username" label="登录账号" :rules="[{min:2,max:15,message:'2~15个字符',trigger:'blur'}]">
                            <Input v-model="teacher.username" disabled placeholder="请输入登录账号" style="width: 300px" :maxlength="15" prefix="ios-paper-outline" show-word-limit />
                        </FormItem>
                        <FormItem prop="password" label="登录密码" :rules="[{min:2,max:40,message:'2~40个字符',trigger:'blur'}]">
                            <Input v-model="teacher.password" disabled placeholder="请输入登录密码" style="width: 300px" :maxlength="40" prefix="ios-unlock-outline" show-word-limit />
                        </FormItem>
                        <FormItem prop="telephone" label="手机号码" :rules="[{validator:$validated.isTelephone},{min:11,max:11,message:'只能输入11个字符',trigger:'blur'}]">
                            <Input v-model="teacher.telephone" :disabled="ok" placeholder="请输入手机号码" style="width: 300px" :maxlength="11" prefix="ios-phone-portrait" show-word-limit />
                        </FormItem>
                        <FormItem prop="email" label="邮箱账号" :rules="[{validator:$validated.isEmail},{min:5,max:30,message:'只能输入5~30个字符',trigger:'blur'}]">
                            <Input v-model="teacher.email" :disabled="ok" placeholder="请输入正确的邮箱账号" style="width: 300px" :maxlength="30" prefix="ios-at-outline" show-word-limit />
                        </FormItem>
                        <FormItem prop="sex" label="教师性别" :rules="[{required:true,message:'请选择教师性别',trigger:'change'}]">
                            <Select v-model="teacher.sex" disabled placeholder="请选择教师性别" prefix="logo-reddit" style="width: 300px">
                                <Option value="1" label="男"></Option>
                                <Option value="2" label="女"></Option>
                            </Select>
                        </FormItem>
                        <FormItem prop="birthday" label="教师生日">
                            <DatePicker v-model="teacher.birthday" prefix="ios-list-box-outline" disabled format="yyyy-MM-dd" style="width: 300px" placeholder="请选择教师生日"></DatePicker>
                        </FormItem>

                    </Col>
                    <Col :span="10">
                        <FormItem label="员工照片">
                            <el-upload
                                    :disabled="ok"
                                    ref="upload"
                                    name="file"
                                    class="upload-demo"
                                    drag
                                    :limit="1"
                                    :auto-upload="true"
                                    list-type="picture-card"
                                    :file-list="fileList"
                                    :data="{id: (teacher.id || '') }"
                                    :headers="{'token': token()}"
                                    action="http://39.106.107.155:56700/image/upload"
                                    :on-success="uploadSuccess"
                                    :on-exceed="uploadExceed"
                                    :before-upload="beforeUpload"
                                    :on-error="uploadError">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text"><em>点击上传</em></div>
                                <div class="el-upload__tip" slot="tip">只支持JPG、JPEG、PNG格式的图片文件，且不超过2MB</div>
                            </el-upload>
                            <p style="color: #969896"> <span style="color:red;">*</span> 请上传职工工装正脸照片,用于系统刷脸登录,非脸照将无法登录</p>
                        </FormItem>
                    </Col>
                </Row>


                <FormItem label="选省市区">
                    <el-cascader size="mini" :disabled="ok" :options="options" v-model="address" style="width: 300px;"></el-cascader>
                </FormItem>

                <FormItem prop="township" label="乡镇信息" :rules="[{required:true,message:'必填',trigger:'blur'},{min:2,max:15,message:'2~15个字符',trigger:'blur'}]">
                    <Input v-model="teacher.township" :disabled="ok" placeholder="请输入乡镇信息" style="width: 300px" :maxlength="15" prefix="ios-tablet-landscape" show-word-limit />
                </FormItem>

                <FormItem prop="detailed" label="村或街道" :rules="[{required:true,message:'必填',trigger:'blur'},{min:2,max:10,message:'只能输入2~10个字符',trigger:'blur'}]">
                    <Input v-model="teacher.detailed" :disabled="ok" placeholder="请输入村或街道" style="width: 300px" :maxlength="10" prefix="md-tablet-landscape" show-word-limit />
                </FormItem>
                <FormItem prop="emergencyRelation" label="联络关系" :rules="[{required:true,message:'必填',trigger:'blur'},{min:2,max:5,message:'2~5个字符',trigger:'blur'}]">
                    <Input v-model="teacher.emergencyRelation" placeholder="请输入当前教师与紧急联络人的关系" :disabled="ok" style="width: 300px" :maxlength="5" prefix="ios-person-add-outline" show-word-limit />
                </FormItem>

                <Divider orientation="right">学历信息</Divider>

                <FormItem prop="graduationSchool" label="毕业院校" :rules="[{required:true,message:'必填',trigger:'blur'},{min:3,max:18,message:'3~18个字符',trigger:'blur'}]">
                    <Input v-model="teacher.graduationSchool" placeholder="请输入毕业院校" :disabled="ok" style="width: 300px" :maxlength="30" prefix="ios-home-outline" show-word-limit />
                </FormItem>
                <FormItem prop="education" label="教师学历" :rules="[{required:true,message:'请选择教师学历',trigger:'change'}]">
                    <Select v-model="teacher.education" :disabled="ok" placeholder="请选择教师学历" prefix="md-heart-outline" style="width: 300px">
                        <Option value="初中" label="初中"></Option>
                        <Option value="高中" label="高中"></Option>
                        <Option value="中专" label="中专"></Option>
                        <Option value="大专" label="大专"></Option>
                        <Option value="本科" label="本科"></Option>
                        <Option value="硕士" label="硕士"></Option>
                        <Option value="其他" label="其他"></Option>
                    </Select>
                </FormItem>
                <FormItem prop="major" label="教师专业" :rules="[{required:true,message:'请选择教师专业',trigger:'change'}]">
                    <Select v-model="teacher.major" :disabled="ok" placeholder="请选择教师专业" prefix="ios-infinite-outline" style="width: 300px">
                        <Option value="计算机" label="计算机"></Option>
                        <Option value="其他" label="其他"></Option>
                    </Select>
                </FormItem>

                <FormItem prop="emergencyContact" label="联系方式" :rules="[{required:true,message:'必填',trigger:'blur'},{min:11,max:20,message:'11~20个字符',trigger:'blur'}]">
                    <Input v-model="teacher.emergencyContact" placeholder="联络人姓名+电话" :disabled="ok" style="width: 300px" :maxlength="20" prefix="ios-person-add-outline" show-word-limit />
                </FormItem>
                <Divider orientation="right">资历信息</Divider>

                <FormItem prop="entryTime" label="入职日期" :rules="[{type:'date',required:true,message:'必选',trigger:'change'}]">
                    <DatePicker v-model="teacher.entryTime" :disabled="ok" format="yyyy-MM-dd" style="width: 300px" placeholder="请选择教师入职日期"></DatePicker>
                </FormItem>

                <FormItem prop="identityId" label="教师身份" :rules="[{required:true,message:'请选择教师身份',trigger:'change'}]">
                    <Select v-model="teacher.identityId" :disabled="ok" placeholder="请选择教师身份" prefix="ios-infinite-outline" style="width: 300px">
                        <Option :value="identity.id" :label="identity.name" v-for="identity in identities" :key="identity.id"></Option>
                    </Select>
                </FormItem>
            </Form>
        </Card>
    </div>
</template>

<script>

    import { getToken } from '@/utils/tool'
    import { regionData,CodeToText,TextToCode } from 'element-china-area-data'
    import { saveOrUpdateTeacher,searchTeacher } from '@/api/principal/school-manager/teacher'
    import { searchDepartmentBySchool } from '@/api/principal/school-manager/school'
    import { search } from '@/api/system/dictionary/index'
    export default {
        name: "school-teacher-scanner",
        data(){
            return {
                teacher:{},
                ok:true,
                show:false,
                fileList:[],
                fullscreenLoading:false,
                quillUpdateImg:false,
                options: regionData,
                departmentList:[],
                address:[],
                identities:[]
            }
        },
        methods: {
            token(){
                return getToken();
            },
            uploadError(err,file,fileList){
                this.$message.error(file.name + "文件上传失败");
                return false;
            },
            uploadExceed(){
                this.$message.error("上传的文件超出了限定了个数");
                return false;
            },
            beforeUpload(file){
                const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
                const isLt1M = file.size / 1024 / 1024 < 1;
                if (!isJPG) {
                    this.$message.error('支持JPG、PNG格式的图片，大小不得超过1M');
                }
                if (!isLt1M) {
                    this.$message.error('文件最大不得超过1M');
                }

                isJPG && isLt1M ? this.quillUpdateImg = true : this.quillUpdateImg = false;

                return isJPG && isLt1M;

            },
            uploadSuccess(response,file,filelist){
                if(response.success){
                    this.teacher.url = response.data.url;
                    this.teacher.id = response.data.id;
                }
            },
            createUsername() {
                if(this.teacher.nickName){
                    let pinyin = require('js-pinyin');
                    pinyin.setOptions({checkPolyphone: false, charCase: 0});
                    let name = pinyin.getCamelChars(this.teacher.nickName).toLowerCase();
                    let random = Math.floor(Math.random() * (9999 - 999) + 999) ;
                    this.teacher.username = name + random;
                    this.teacher.password = "123456";
                }else{
                    this.teacher.username = null;
                    this.teacher.password = null;
                }
            },
            onValidate(prop, status, error){
                if(prop === 'idCard' && status == true){
                    let idCard = this.teacher.idCard;
                    let sex = "0";
                    let birth = idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14);
                    if(parseInt(idCard.substr(16, 1)) % 2 == 1) {
                        //男
                        sex = '1';
                    } else {
                        //女
                        sex = '2';
                    }

                    this.teacher.sex = sex;
                    this.teacher.birthday = birth;
                    this.ok = false;
                    this.show = true;
                }else if(prop === 'idCard' && status == false){
                    this.ok = true;
                }
            },
            searchTeacher(idCard){
                this.address = [];
                searchTeacher({idCard:idCard}).then(res=>{
                    if(res.data.data && res.data.data.id){
                        res.data.data.entryTime = new Date(res.data.data.entryTime);
                        res.data.data.birthday = new Date(res.data.data.birthday);
                        this.teacher = res.data.data;
                        this.address.push(TextToCode[res.data.data.province].code);
                        this.address.push(TextToCode[res.data.data.province][res.data.data.city].code);
                        this.address.push(TextToCode[res.data.data.province][res.data.data.city][res.data.data.area].code);
                        let obj = new Object();
                        obj.url = res.data.data.url;
                        this.fileList.push(obj)
                    }
                })
            },
            handleSubmit(){
                if(!this.address || this.address.length == 0){
                    this.$message.error("请选择省市区");
                    return false;
                }

                if(this.$refs.upload.uploadFiles.length != 1){
                    this.$message.error("请选择文件");
                    return false;
                }

                this.$refs['form'].validate(valid=>{
                    if(valid){
                        this.teacher.type = '1';
                        this.teacher.status = '1';
                        this.teacher.level = "user";
                        this.teacher.hasLevel = "1";
                        this.teacher.hasMember = "2";
                        this.teacher.laborContract = "2";
                        this.teacher.hasSocialSecurity = "2";

                        let arr = [];
                        this.address.forEach(ele=>arr.push(CodeToText[ele]));

                        //给省市区赋值
                        this.teacher.province = arr[0];
                        this.teacher.city = arr[1];
                        this.teacher.area = arr[2];

                        this.$confirm("你确定提交吗?","友情提示",{type:'warning'}).then(()=>{
                            this.fullscreenLoading = true;
                            saveOrUpdateTeacher(this.teacher).then(res=>{
                                this.$refs.upload.uploadFiles = [];
                                this.fileList = [];
                                this.teacher = {};
                                this.ok = true;
                                this.show = false;
                                this.address = [];
                                this.$refs['form'].resetFields();
                                this.fullscreenLoading = false;
                            })
                        });

                    }else{
                        return false;
                    }
                });
            }
        },
        mounted(){
            this.$refs.upload.uploadFiles = [];
            this.fileList = [];
            search({code:'JOB-IDENTITY'}).then(res=>{
                this.identities = res.data.data;
            })
        }
    }
</script>

<style>

</style>